package com.yoyo.itravel.utils;

import org.jsoup.Connection;
import org.jsoup.Connection.Response;
import org.jsoup.Jsoup;

import java.io.IOException;

/**
 * @Description 爬虫工具类
 * 
 * @author HZX
 * @date 2020年4月25日 下午1:09:17
 */
public class JsoupUtils {
	
	private JsoupUtils() {
		
	}
	
	private static final String WEATHER_URL = "http://wthrcdn.etouch.cn/weather_mini";
	private static final String WEATHER_KEY = "city";
	
	/**
	 * @Description 获得访问爬取的url
	 *
	 * @param cityName
	 * @return
	 */
	public static String getUrl(String cityName) {
		return WEATHER_URL + "?" + WEATHER_KEY + "=" + cityName;
	}
	
	public static String getWeatherByCityName(String cityName) throws IOException {
		// 非空判断
		if (StringUtils.isEmpty(cityName)) {
			throw new RuntimeException("您传入的城市名称非法...");
		}
		// 通过url构建一个链接对象
		Connection connect = Jsoup.connect(getUrl(cityName));
		// 忽略一些错误信息
		connect.ignoreContentType(true).ignoreHttpErrors(true);
		// 执行请求，获得响应对象
		Response response = connect.execute();
		// 获得响应结果的二进制数组
		byte[] bytes = response.body().getBytes();
		// 指定编码，返回字符串
		return new String(bytes, "UTF-8");
	}
	
	public static void main(String[] args) throws IOException {
		
		System.out.println(getWeatherByCityName("长沙"));
	}

}
